<?php 
	require_once("init.php");  
?>

<?php 
	$userId = 1;
	if (isset($_SESSION["userId"])) {
		$userId = $_SESSION["userId"];
	}

	$strCheckVote = "
		SELECT voteId
		FROM votes
		WHERE topicId = ".$_GET["id"]."
	";
	if (isset($_SESSION["userId"])) {
		$strCheckVote = $strCheckVote."
			AND userId = ".$_SESSION["userId"]."
		";
	} else if (strlen(session_id()) > 0) {
		$strCheckVote = $strCheckVote."
			AND sessionId = '".session_id()."'
		";
	} else {
?>
<div id="vote-fail" title="Oops!" class="panel">
	<p>Oops! You must be signed in to do this.</p>
</div>
<?php
		die("Oops! You must be signed in to do this.");
	}
	$qCheckVote = mysql_query($strCheckVote);
	
	// if vote is already made, display error message
	if (mysql_num_rows($qCheckVote) > 0) {
?>

<div id="vote-fail" title="Oops!" class="panel">
	<p>You have previously voted on this topic. Please select another topic.</p>
</div>

<?php
	} else {
		// Add user's vote
		$qInsertVote = mysql_query("
			INSERT INTO votes (
				topicId,
				userId,
				sessionId,
				answer,
				dateVoted
			)
			VALUES (
				".$_GET["id"].",
				".$userId.",
				'".session_id()."',
				'".$_GET["a"]."',
				now()
			)
		");
		
		// Update the number
		$qUpdateVoteNumbers = mysql_query("
			UPDATE topics
			SET 
				answer".$_GET["a"]."Votes = answer".$_GET["a"]."Votes + 1
			WHERE 
				topicId = ".$_GET["id"]."
		");
		
		// Update user points
		if (isset($_SESSION["userId"])) {
			$qUpdateUserPoints = mysql_query("
				UPDATE users
				SET 
					points = points + ".$voteTopicPoints."
				WHERE 
					userId = ".$_SESSION["userId"]."
			");
		}
		
		$qGetVote = mysql_query("
			SELECT answer1Votes, answer2Votes
			FROM topics
			WHERE topicId = ".$_GET["id"]."
		");
		$vote = mysql_fetch_array($qGetVote);
		
		print $_GET["id"]."|".$_GET["a"]."|".$vote["answer1Votes"].",".$vote["answer2Votes"];
	}
?>

<?php 
	require_once("end.php"); 
?>